﻿
CREATE FUNCTION [dbo].[GetStocIesiri]
(
	@CodUnitate smallint,
	@IDArticol int,
	@Pret decimal(25,5)	
)
RETURNS decimal(25,5)
AS
BEGIN

	DECLARE @ResultVar decimal(25,5)
	DECLARE @StocCantitativ bit
	SET @StocCantitativ = 0
	SET @ResultVar = 0
	
	SELECT @StocCantitativ = GestiuneCantitativa  FROM FaresSetup WHERE CodUnitate = @CodUnitate

	IF @StocCantitativ=0 
	BEGIN
		SELECT @ResultVar = COALESCE(SUM(ddl.Cantitate),0) FROM DocumenteDetaliu dd 
		JOIN Documente d ON d.IDDocument=dd.IDDocument
		JOIN DocumenteDetaliuLink  ddl ON ddl.IDDocDetaliuSursa = dd.IDDocumentDetaliu
		JOIN DocumenteDetaliu ddr ON ddl.IDDocDetaliuDest = ddr.IDDocumentDetaliu
		JOIN Documente dr ON ddr.IDDocument = dr.IDDocument
		WHERE dd.IDArticol=@IDArticol AND dd.ValoareUnitara=@Pret AND 
		(d.IDTipDocument = 0 OR d.IDTipDocument = 15) AND d.AreDocGestStoc=1 AND 
		(dr.IDTipDocument in (1,13,14)) AND dr.AreDocGestStoc=1
	END
	ELSE
	BEGIN
		SELECT @ResultVar = COALESCE(SUM(dd.Cantitate),0) FROM DocumenteDetaliu dd 
		JOIN Documente d ON d.IDDocument=dd.IDDocument
		WHERE dd.IDArticol=@IDArticol  AND 
		(d.IDTipDocument in (1,13,14)) AND d.AreDocGestStoc=1	
	END
	
	RETURN @ResultVar

END